package main

import (
	"database/sql"
	"fmt"
	"strconv"
)

type TraBlockChain struct{
	//区块链，存储区块顺序和结构
	blockList []traBlock
	db *sql.DB
}

//赋值数据库指针
func NewTraBlockChain(db *sql.DB) *TraBlockChain {
	bc := new(TraBlockChain)
	bc.db = db
	return bc
}

//向区块链中添加区块
func (l *TraBlockChain)AddBlock(db *sql.DB, b *traBlock){
	//if len(l.blockList) > 0 {
	//	b.prevHash = l.blockList[len(l.blockList)-1].hash
	//}
	b.LinkBTrf(db)
	b.Seal()
	l.Validate(b)
	l.blockList = append(l.blockList, *b)
	InsertBTrf(l.db,"bTrf", b.prevHash,
		b.hash, strconv.FormatInt(b.EventID,10), b.srcAddress,
		b.dstAddress, b.message)
}

//向区块链中添加区块
func (l *TraBlockChain)AddBrTrfBlock(db *sql.DB, b *traBlock){
	b.LinkBrTrf(db)
	b.Seal()
	l.Validate(b)
	l.blockList = append(l.blockList, *b)
	InsertBrTrf(l.db,"brTrf", b.prevHash,
		b.hash, strconv.FormatInt(b.EventID,10),
		b.srcAddress, b.dstAddress, b.hash)
}

//验证区块链
func (l *TraBlockChain)Validate(b *traBlock){
	for i,block := range l.blockList{
		block.Validate()
		err := recover() //获取异常
		if err != nil {
			fmt.Println("第" + strconv.Itoa(i) + "块区块内容被篡改")
		}
	}
}